/**
* Class Name: ifulfillNewCustomQueryController
* Author: Accenture IDC | Bhumika Udani
* Date: December -2011
* Requirement/Project Name: ifulfill
* Requirement/Project Description: Used to override the standard page for create and Edit Query Request
* Bhumika Udani      10 Decemeber 2011              v1.0  Custom create query request page
* Bhumika Udani      21 Decemeber 2011              v1.1  Included the dependency between Query Request Type and Request Reason
* Bhumika Udani      05 January 2012                v1.2  Updated as per peer review comments
**/

public class ifulfillNewCustomQueryController
{
    public Query_Request__c queryRequest{get;set;}
    public fullfilment_item__c fItem{get;set;}
    public string requestor {get;set;}
    public date reqDate {get;set;}
    public Boolean renderKeepItWithMe {get;set;}
    public string requestType{get;set;}
    public List<SelectOption> requestReason{get;set;}
    private ApexPages.StandardController contrl = null;
    /** Constructor **/
    public ifulfillNewCustomQueryController(ApexPages.StandardController controller) {


        contrl = controller;
        renderKeepItWithMe = false;
        reqDate = system.today();
        requestor = UserInfo.getName(); 
        requestType ='';
        
        queryRequest = (Query_Request__c)controller.getRecord();
        /**Re render the selected Request Reason in Edit mode**/    
        if(queryRequest.id != null || queryRequest.id != '' ){
        
            requestType = queryRequest.Request_Reason__c;
        }
        /**Check if the Query Request is attached to the Fulfillment item, if so fetch more info and display on the vf page **/
        
        if(queryRequest.Fulfillment_Item__c != null){
        
            fItem = [select id,Workflow_Coordinator__c,Feature_Code__c,Aging__c,Status__c,UDAC_Description__c,Function_Sequence__c, UDAC__c, Current_Function_Name__c,Current_Task_Name__c,Item_Id__c, Account__r.Name,Item_Version__c, Region__c,Feature__c, Contract__c,Contract_Version__c,Product_Issue__c,Customer_ID__c, Product_Code__c from fullfilment_item__c where id =:queryRequest.Fulfillment_Item__c];    
            System.debug('fItem status'+fItem.Status__c); 
            System.debug('queryRequest data'+queryRequest);
            System.debug('Query request workflow status'+queryRequest.Workflow_Status__c); 
            if(queryRequest.Workflow_Status__c == null){  
               queryRequest.Workflow_Status__c = fItem.Status__c;             
            }  
            if(fItem.Function_Sequence__c ==1)
            {          
                 /**For sequence 1 the query request needs to be of type - Initial Fulfillment **/
                 renderKeepItWithMe = true;
                 queryRequest.Query_Type__c=IfullfillTextConstant.QUERY_INIT_TYPE;     
                 queryRequest.Keep_it_with_me__c  =renderKeepItWithMe;
            }
            else
            {
                /**Else it has be of type Mid Fulfillment type **/

                queryRequest.Query_Type__c=IfullfillTextConstant.QUERY_MID_TYPE;
                
                /** If its Out of Region Query Request and Workflow coordinator isn't null assign the Query Request to the workflow coordinator **/
                if(fItem.Region__c !=null && fItem.Region__c.equalsIgnoreCase(IfullfillTextConstant.FI_WORKFLOW_OOR_REG) && fItem.Workflow_Coordinator__c != null && queryRequest.name == null)
                {
                   queryRequest.ownerId =  fItem.Workflow_Coordinator__c;
                }
            }
        }
    }
        
    /**Below method is used to populate the drop down selection for Request reason (Dependent picklist)**/
    public  void displayRequestReason(){
            /**Fetch the picklist values for Request reason field**/
            requestReason = new List<SelectOption>();
            Schema.DescribeFieldResult reqReasonResult = Query_Request__c.Request_Reason__c.getDescribe();        
 
            if(queryRequest.Query_Type__c==IfullfillTextConstant.QUERY_INIT_TYPE)
            {     
                 for(Schema.PickListEntry reasonPickVal : reqReasonResult.getPicklistValues())
                 {            
                        
                        /**Don't include the dependent value for Initial fulfillment Query Request Type **/
                        
                        if(reasonPickVal.getLabel() == IfullfillTextConstant.QUERY_INIT_REASON || reasonPickVal.getLabel() == IfullfillTextConstant.PICKLIST_NONE_TXT )
                        {
                            requestReason.add(new SelectOption(reasonPickVal.getValue(),reasonPickVal.getLabel()));       
                        }
                    }
                    
            }
            else if(queryRequest.Query_Type__c==IfullfillTextConstant.QUERY_MID_TYPE){
                
                for(Schema.PickListEntry reasonPickVal : reqReasonResult.getPicklistValues()){            
                        if(reasonPickVal.getLabel() != IfullfillTextConstant.QUERY_INIT_REASON){
                           requestReason.add(new SelectOption(reasonPickVal.getValue(),reasonPickVal.getLabel()));       
                         }
                     }
            } 
                  
    }
    /*
     *  Override  standard Save Action
     *
     **/
     public PageReference save()   
     {  
          queryRequest.Request_Reason__c = requestType;  
            
          return contrl.save();   
     }
   
    /*
     *  Test Method 
     *
     **/
     
     
   
     static testMethod void testController()
     {
     
            List<Sobject>  sobjList = new List <Sobject>();
       Profile p = [select id from profile where name='System Administrator'];
       User u1 = new User(alias = 'MoveNex', email='MoveNextsystemadmin@accenture.com',emailencodingkey='UTF-8', lastname='Controller', languagelocalekey='en_US',localesidkey='en_US', profileid = p.Id,timezonesidkey='Asia/Calcutta', username='ifulfillNexttestad@testorg.com');                   
       User u2 = new User(alias = 'workflow', email='coorsystemadmin@accenture.com',emailencodingkey='UTF-8', lastname='Coordinator', languagelocalekey='en_US',localesidkey='en_US', profileid = p.Id,timezonesidkey='Asia/Calcutta', username='workflowCoord@testorg.com');                    
       sobjList.add(u1);
       sobjList.add(u2);

       Insert sobjList;
         /**Fulfillment Item 2 for ifulfillNewCustomQueryController controller**/
       Fullfilment_Item__c FI2 = new Fullfilment_Item__c();
       FI2.Main_Listing_Phone_Number__c = '100';
       FI2.Listed_Name__c ='Custom Query XYZ';
       FI2.Heading_Name__c ='Custom Query Heading name';
       FI2.Product_Code__c = 'Cus Que ';
       FI2.UDAC__c = 'Custom Query UDAC';
       FI2.Region__c = 'In-Region East' ;
       FI2.Transaction_Type__c = 'New';
             
       insert FI2; 
       
       Fullfilment_Item__c  tempFI = [select ownerID  from Fullfilment_Item__c  where id = :FI2.id ];
       tempFI.ownerID = u1.id;     
       update tempFI;       
       
       // create a query request record on FI2 fulfillment item
       Query_Request__c testQueryRequest = new Query_Request__c();
       testQueryRequest.Fulfillment_Item__c = tempFI.id;
       testQueryRequest.Request_Reason__c = IfullfillTextConstant.QUERY_INIT_REASON;
       
       system.runAs(u1){
       insert testQueryRequest;
       }

       // set the page reference to the custom vf page used to create query request record
       PageReference queryPageRef = Page.ifulfillNewCustomQuery;
       Test.setCurrentPage(queryPageRef);
              
       ApexPages.StandardController queryCtrl = new ApexPages.StandardController(testQueryRequest);            
       ifulfillNewCustomQueryController customController = new ifulfillNewCustomQueryController(queryCtrl);
       customController.displayRequestReason();
       
       // update the FI2 to change the region and to move the FI item ahead in workflow definition
       /**FI2.Current_Stage__c = WFS1.id;
       FI2.Current_Step__c = wfSteps1.id;       
       FI2.Region__c ='Out-of-Region';
       FI2.ownerid = u2.id;
       update FI2;**/
       
       // Create another query request under mid fulfillment item
       
       Query_Request__c testQueryRequest2 = new Query_Request__c();
       testQueryRequest2.Fulfillment_Item__c = FI2.id;
       
       Test.setCurrentPage(queryPageRef);
       
       ApexPages.StandardController queryCtrl2 = new ApexPages.StandardController(testQueryRequest);            
       ifulfillNewCustomQueryController customController2 = new ifulfillNewCustomQueryController(queryCtrl2);
       customController2.displayRequestReason();

     }
}